package com.weizhong.update.service;

import java.io.File;import android.app.DownloadManager;import android.app.Service;import android.app.DownloadManager.Request;import android.content.Context;import android.content.Intent;import android.net.Uri;import android.os.IBinder;import android.os.PowerManager;import android.text.TextUtils;import android.util.Log;import android.view.View;import com.weizhong.update.R;import com.weizhong.update.model.AppEntity;import com.weizhong.update.util.Constances;import com.weizhong.update.util.FileTool;import com.weizhong.update.util.Logger;import com.weizhong.update.util.UpdateDetail;

public class AppUpdateService extends Service {
	private static final String TAG = "AppUpdateService";
	private UpdateDetail updateDetail;		private AppUpdateDownloadListener appUpdateDownloadListener;
	private long fileSize;	
	private DownloadManager mgr;	
	private long lastDownload =0;	
	private PowerManager.WakeLock wakeLock = null; 
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void onCreate() {		appUpdateDownloadListener = new AppUpdateDownloadListener(this);
		// TODO Auto-generated method stub
		super.onCreate();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {		
		Logger.i(TAG, "onstartCommand");
		if(intent==null)
			return 0;		AppEntity appEntity = (AppEntity) intent.getSerializableExtra("appentity");		
		updateDetail = new UpdateDetail(this);		Log.i(TAG,"appEntity download id: " + appEntity.getDownloadID());		//存在		if(appEntity.getDownloadID() > 0){			Logger.i(TAG, appEntity.getPackageName() + "已在下载列表，查询下载状态");			if(appUpdateDownloadListener == null){				appUpdateDownloadListener = new AppUpdateDownloadListener(this);			}			if(appUpdateDownloadListener != null){				int status = appUpdateDownloadListener.getDownloadStatus(appEntity.getDownloadID());				Log.i(TAG, "status: " + status);				if (status == 0 || status == DownloadManager.STATUS_FAILED){					mgr = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);					mgr.remove(appEntity.getDownloadID());					String downloadUrl = appEntity.getApkPath();										if (downloadUrl != null){						this.fileSize = appEntity.getApkSize();						mgr = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);						if(!TextUtils.isEmpty(downloadUrl))							download(downloadUrl,appEntity.getPackageName());					}				}else {					appUpdateDownloadListener.addToListener(appEntity.getDownloadID(), appEntity.getPackageName());					appUpdateDownloadListener.queryAppDownloadStatus();				}			}		}else {			String downloadUrl = appEntity.getApkPath();						if (downloadUrl != null){				this.fileSize = appEntity.getApkSize();				mgr = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);				if(!TextUtils.isEmpty(downloadUrl))					download(downloadUrl,appEntity.getPackageName());			}		}
		return super.onStartCommand(intent, flags, startId);
	}
	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();		if(appUpdateDownloadListener != null){			appUpdateDownloadListener.destroyMap();		}		appUpdateDownloadListener = null;		stopSelf();
	}
	/**
	 * 下载
	 */
	private void download(final String downloadUrl,final String packageName){		
		new Thread(new Runnable() {
			@Override
			public void run() {				
				startDownload(downloadUrl,packageName);
			}
		}
		).start();
	}
	
    public void startDownload(String downloadUrl,String packageName) {    	    	Logger.i(TAG, "downloadURL is: " + downloadUrl);
        Uri uri = Uri.parse(downloadUrl);         //String fileName = FileTool.getApkDownFileName(downloadUrl);                String fileName = packageName + ".apk";
        String dirPath = updateDetail.getSdcardPath() + Constances.update_dir;
        try{
	        Request dwreq=new DownloadManager.Request(uri);	        	        File file = new File(dirPath+"/"+fileName);	        	        if(file.exists()){	        	file.delete();	        }
	        Uri dpath= Uri.fromFile(new File(dirPath+"/"+fileName));
	        dwreq.setDestinationUri(dpath);
	        dwreq.setTitle(getResources().getString(R.string.apk_notification_string)); 
	        dwreq.setVisibleInDownloadsUi(false);
	        dwreq.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
	        dwreq.setDescription(getResources().getString(R.string.percent_update));	       	        long downloadID;	        downloadID = mgr.enqueue(dwreq,false);	        appUpdateDownloadListener.addToListener(downloadID, packageName);
        }catch(Exception e){
        	e.printStackTrace();
        }
    }
  //查看下载窗口
    public void viewDownWindow(View v) {
        startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)); 
    }        
    private void releaseWack(){
    	if (wakeLock != null) {  
            wakeLock.release();  
            wakeLock = null;  
        }  
    }   }